import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:riki_base_flutter/riki_base_flutter.dart';
import 'package:riki_push/entity/push_info_entity.dart';
import 'package:riki_push/enum/phone_platform.dart';
import 'package:riki_push/factory/riki_base_push.dart';
import 'package:riki_push/factory/riki_hw_push.dart';
import 'package:riki_push/factory/riki_meizu_push.dart';
import 'package:riki_push/factory/riki_oppo_push.dart';
import 'package:riki_push/factory/riki_xm_push.dart';
import 'package:riki_push/factory/riki_vivo_push.dart';
import 'package:riki_push/riki_push.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  TextEditingController controller = TextEditingController();
  Map<String, Function> methods = {};

  // --------------- android厂商的相关参数 ---------------

  static const String xm_appId = '2882303761519019908';
  static const String xm_appKey = '5781901981908';
  static const String jpush_app_key = '342c310ced56272ea79fd1d1';
  static const String oppo_appKey = 'fde290a9deec48448046e800bf581a8e';
  static const String oppo_appSecret = '57cf46983dfc4936b8513df87799d75c';
  static const String meizu_appId = '139859';
  static const String meizu_appkey = 'e7187da08a6142418923a4cb1acb10ea';

  @override
  void initState() {
    super.initState();
    RikiBase.init();
    AndroidInitializationSettings initializationSettingsAndroid = new AndroidInitializationSettings('ic_launcher');
    IOSInitializationSettings initializationSettingsIOS = new IOSInitializationSettings();
    RikiPush.instance.init(
        xmAppId: xm_appId,
        xmAppKey: xm_appKey,
        oppoKey: oppo_appKey,
        oppoSecret: oppo_appSecret,
        meizuAppId: meizu_appId,
        meizuAppKey: meizu_appkey,
        jpushAppKey: jpush_app_key,
        jpushChannel: 'theChannel');
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    PhonePlatform platform;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      platform = await RikiBasePush.phonePlatform;
    } on PlatformException {
      platform = PhonePlatform.normal;
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    /// ----------------------   huawei  ------------------------
    if (platform == PhonePlatform.huawei) {
      this.methods = {
        '厂商是': () async => this.controller.text = '${await RikiBasePush.phonePlatform}',
        '获取华为的token': () async => this.controller.text = await RikiHwPush.hwToken,
      };
    }

    /// ----------------------   小米  ------------------------
    if (platform == PhonePlatform.xiaomi) {
      this.methods = {
        '厂商是': () async => this.controller.text = '${await RikiBasePush.phonePlatform}',
        'getXmRegId': () => _getXmRegId(),
        'unInit': () async => await RikiXmPush.unInit()
      };
    }

    /// ----------------------   oppo  ------------------------
    if (platform == PhonePlatform.oppo) {
      this.methods = {
        '厂商是': () async => this.controller.text = '${await RikiBasePush.phonePlatform}',
        'getOppoId': () => _getOppoId(),
        'unInit': () async => await RikiOppoPush.unInit()
      };
    }

    /// ----------------------   vivo  ------------------------
    if (platform == PhonePlatform.vivo) {
      this.methods = {
        '厂商是': () async => this.controller.text = '${await RikiBasePush.phonePlatform}',
        'getVivoId': () => _getVivoId(),
        'unInit': () async => await RikiVivoPush.unInit()
      };
    }

    /// ----------------------   魅族  ------------------------
    if (platform == PhonePlatform.meizu) {
      this.methods = {
        '厂商是': () async => this.controller.text = '${await RikiBasePush.phonePlatform}',
        'getVivoId': () => _getMeizuId(),
        'unInit': () async => await RikiVivoPush.unInit()
      };
    }

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('厂商推送'),
        ),
        floatingActionButton: FloatingActionButton(
          child: GestureDetector(
            onTap: click,
            child: Text('点击'),
          ),
        ),
        body: Center(
          child: Column(
            children: <Widget>[
              TextField(
                controller: controller,
                maxLines: 10,
              ),
              Expanded(
                child: Wrap(
                  runSpacing: 10,
                  spacing: 10,
                  children: methods.keys
                      .map(
                        (key) => RaisedButton(
                          onPressed: methods[key],
                          child: Text(key),
                        ),
                      )
                      .toList(),
                ),
              ),
              Image(
                image: AssetImage("assets/images/space.jpg"),
                width: 100,
              )
            ],
          ),
        ),
      ),
    );
  }

  /// 获取小米的 regid
  _getXmRegId() async {
    await (RikiXmPush.init(appId: '2882303761519019908', appKey: '5781901981908'));
    this.controller.text = '${await RikiXmPush.xmRegId}';
  }

  /// 获取oppo的 id
  _getOppoId() async {
    this.controller.text = '${await RikiOppoPush.oppoRid}';
  }

  /// 获取vivo的 id
  _getVivoId() async {
    this.controller.text = '${await RikiVivoPush.vivoRid}';
  }

  /// 获取vivo的 id
  _getMeizuId() async {
    this.controller.text = '${await RikiMeizuPush.meizuRid}';
  }

  void click() async {
    // await  notification();
    notificationAfterSec();
  }

  Future<void> notification() async {
    AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails('Channel ID', 'Channel title', 'channel body',
        priority: Priority.high, importance: Importance.max, ticker: 'test');
    IOSNotificationDetails iosNotificationDetails = IOSNotificationDetails();
    NotificationDetails notificationDetails = NotificationDetails(android: androidNotificationDetails, iOS: iosNotificationDetails);
    RikiPush.instance.showNotification(333, 'title', 'body', notificationDetails);
  }

  Future<void> notificationAfterSec() async {
    var timeDelayed = DateTime.now().add(Duration(seconds: 5));
    AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails(
        'second channel ID', 'second Channel title', 'second channel body',
        priority: Priority.high, importance: Importance.max, ticker: 'test');
    IOSNotificationDetails iosNotificationDetails = IOSNotificationDetails();
    NotificationDetails notificationDetails = NotificationDetails(android: androidNotificationDetails, iOS: iosNotificationDetails);
    // await flutterLocalNotificationsPlugin.schedule(1, 'Hello there',
    //     'please subscribe my channel', timeDelayed, notificationDetails);
    RikiPush.instance.showNotification(333, 'title', 'body', notificationDetails, payload: '1');
  }
}
